package br.com.ozsolucoes.sessionbeans;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.ozsolucoes.entity.Cliente;
import br.com.ozsolucoes.entity.Servico;
import br.com.ozsolucoes.entity.ServicoCategoria;

@Stateless
public class ServicoSessionBean implements Serializable {

	private static final long serialVersionUID = -3353902316808034524L;

	@PersistenceContext
	private EntityManager entityManager;

	public void cancelarServico(Servico servico) {
		entityManager.merge(servico);
	}

	public void contratarServicoCategoria(ServicoCategoria servicoCategoria) {
		entityManager.persist(servicoCategoria);
	}
	public void removerServicoCategoria(ServicoCategoria servicoCategoria){
		servicoCategoria = entityManager.find(ServicoCategoria.class, servicoCategoria.getPk());
		entityManager.remove(servicoCategoria);
	}

	public void contratarServico(Servico servico) {
		Cliente cliente = entityManager.find(Cliente.class, servico.getCliente().getId());
		servico.setCliente(cliente);
		servico.setId(0);
		entityManager.persist(servico);
	}

	public void alterarServico(Servico servico) {
		entityManager.merge(servico);
	}

	public Servico consultarServicoVingente(long idCliente) {
		Query query = entityManager.createNamedQuery("Servico.consultarServicoVingente");
		query.setParameter("idCliente", idCliente);
		query.setParameter("status", 1);
		try {
			return (Servico) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public boolean verificarServicoVingente(long idCliente) {
		Query query = entityManager.createNamedQuery("Servico.consultarServicoVingente");
		query.setParameter("idCliente", idCliente);
		query.setParameter("status", 1);
		try {
			query.getSingleResult();
			return true;
		} catch (NoResultException e) {
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Servico> consultarTodosServicosCliente(long idCliente) {
		Query query = entityManager.createNamedQuery("Servico.consultarTodosServicosCliente");
		query.setParameter("idCliente", idCliente);
		try {
			return query.getResultList();
		} catch (NoResultException e) {
			return null;
		}
	}

}
